package com.gl.sass.mq.factory;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.gl.sass.mq.producer.RocketMQProducer;
import com.gl.sass.mq.properties.BaseProperties;

/**
 * 
 * @author xiehong
 *
 */
@Component
public class ProduceFactory {

    private String groupName = "group_gl_service";

    @Value("${mq.namesrvAddr}")
    private String namesrvAddr;

    public RocketMQProducer buildRocketMQProducer() throws MQClientException {
        return buildRocketMQProducer(build());
    }

    public RocketMQProducer buildRocketMQProducer(BaseProperties baseProperties) throws MQClientException {
        if (baseProperties.isValid()) {
            return new RocketMQProducer(buildDefaultMQProducer(baseProperties));
        }
        return null;
    }

    public DefaultMQProducer buildDefaultMQProducer(BaseProperties baseProperties) throws MQClientException {
        DefaultMQProducer producer = getProducer(baseProperties);
        producer.setRetryAnotherBrokerWhenNotStoreOK(true);
        producer.start();
        return producer;
    }

    public DefaultMQProducer getProducer(BaseProperties baseProperties) {
        DefaultMQProducer producer = new DefaultMQProducer(baseProperties.getGroupName());
        producer.setNamesrvAddr(baseProperties.getNamesrvAddr());
        return producer;
    }

    public BaseProperties build() {
        return new BaseProperties().setGroupName(groupName).setNamesrvAddr(namesrvAddr);
    }
}
